// "ui"

auto();

var z1, z2;
var stopAll = false;
//存储
var storage = storages.create("tb_live_reply.js");

var window = floaty.window(
    <frame gravity="center">
        <vertical w="*" h="*" margin="6" background='#66000000'>
            <text id="title" text="直播助手" gravity="top|center" textColor="red" textSize="13sp" margin="0 5" />
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal >
                <text h="30" text="  输入频率：" gravity="top|left" textColor="white" />
                <text id="inputHz" text="200" hint="200" marginBottom="-6" textColor="white"/>
            </horizontal>
            <horizontal >
                <text h="30" text="  发送频率：" gravity="top|left" textColor="white" />
                <text id="sendHz" text="600" hint="600" marginBottom="-6" textColor="white"/>
            </horizontal>
            {/* <frame w="*" margin="12" h="1" bg="#e3e3e3" /> */}
            <horizontal >
                <text h="30" text="  口令：" gravity="top|left" textColor="white" />
                <text id="keyword" text="暴富" hint="暴富" marginBottom="-6" textColor="red"/>
            </horizontal>
            <frame w="*" margin="12" h="1" bg="#e3e3e3" />
            <horizontal gravity="top|center">
                <button id="runButton" style="Widget.AppCompat.Button.Colored" text="开始" w="auto" h="*" />
                <button id="stopUi" style="Widget.AppCompat.Button.Colored" text="退出" w="auto" h="*" />
            </horizontal>
            {/* <horizontal >
                <text id="logText" background='#ff0000ff' layout_width="0pt" layout_height="wrap_content" layout_weight='4' gravity="center" size="13dp" color="white" text='第三块' />
            </horizontal> */}
        </vertical>
    </frame>
);


window.setPosition(device.width / 2 - 400, device.width / 2 - 400);
window.exitOnClose();

window.title.on("click", () => {
    //开启位置调整
    window.setAdjustEnabled(!window.isAdjustEnabled());
});

window.inputHz.on("click", () => {
    let code = window.inputHz.text();
    dialogs.rawInput("请输入", code)
        .then(code => {
            if (!code) {
                ui.finish();
                return;
            }
            ui.run(function () {
                window.inputHz.setText(code);
            });
        });
});

window.sendHz.on("click", () => {
    let code = window.sendHz.text();
    dialogs.rawInput("请输入", code)
        .then(code => {
            if (!code) {
                ui.finish();
                return;
            }
            ui.run(function () {
                window.sendHz.setText(code);
            });
        });
});

window.keyword.on("click", () => {
    let code = "";
    dialogs.rawInput("请输入", code)
        .then(code => {
            if (!code) {
                ui.finish();
                return;
            }
            ui.run(function () {
                window.keyword.setText(code);
            });
        });
});

//启动
window.stopUi.on("click", () => {
    //程序开始运行之前判断无障碍服务
    // toast("退出");
    // storage.clear();
    stopAll = true;
    console.hide();
    window.close()
    floaty.closeAll()
    if (z1) {
        clearInterval(z1);
    }
    if (z2) {
        clearInterval(z2);
    }
    threads.shutDownAll();
    exit();
});



function initConfig() {
    //用户数据
    ui.run(function () {
        window.inputHz.setText(storage.get("inputHz", "200").toString());
        window.sendHz.setText(storage.get("sendHz", "500").toString());
        window.keyword.setText(storage.get("keyword", "暴富").toString());
    });
 
}
//*******************************************************************初始化设置***************************************************************************************** */
//*******************************************************************主程序***************************************************************************************** */

// 初始化用户配置
//初始化数据
setTimeout(initConfig, 500);

//开启控制台
threads.start(openConsole);

logCommon("直播刷屏模式");
logCommon("请进入直播页面...");

setInterval(() => { }, 1000);

//开始
window.runButton.on("click", () => {

    window.disableFocus();

    var inputHz = window.inputHz.text();
    var sendHz = window.sendHz.text();

    var keyword = window.keyword.text();

    storage.put("inputHz", inputHz);
    storage.put("sendHz", sendHz);
    storage.put("keyword", keyword);

    //启动任务
    if (window.runButton.text() == "开始") {
        stopAll = false;
        //保持屏幕常亮
        device.keepScreenOn();
        //开始任务
        threads.start(function () {
            doJob(keyword, inputHz, sendHz);
        });
        window.runButton.text("停止");
    } else {
        window.runButton.text("开始");
        logError("停止运行...");
        stopAll = true;
        threads.start(function () {
            device.cancelKeepingAwake();
            if (z1) {
                // log("退出z1-")
                clearInterval(z1);
            }
            if (z2) {
                // log("退出z2-")
                clearInterval(z2);
            }
            threads.shutDownAll();
        });
    }

    //保持脚本运行
    // setInterval(() => { }, 1000);
});


function doJob(keyword, inputHz, sendHz) {
    logInfo("开始运行...")
    z1 = setInterval(function () {
        if (className("android.widget.EditText").exists() && !text(keyword).exists() && (textContains("发送").exists() || id("ecv").exists())) {
            logCommon("输入口令：" + setText(keyword));
        } else if (textContains("什么").exists() && !text(keyword).exists() && (textContains("发送").exists() || id("ecv").exists())) {
            logCommon("输入口令：" + setText(keyword));
        } else if (textContains("什么").exists() && !text(keyword).exists() && !textContains("发送").exists() && !id("ecv").exists()) {
            logCommon("打开输入框：" + findClickableItem(textContains("什么").findOne()).click());
        } else if (textContains("聊两句").exists() && !text(keyword).exists() && !textContains("发送").exists() && !id("ecv").exists()) {
            logCommon("打开输入框：" + findClickableItem(textContains("聊两句").findOne()).click());
        }
        if (stopAll) {
            // log("退出z1")
            clearInterval(z1);
        }
        if (stopAll) {
            // log("退出z1")
            clearInterval(z1);
        }
    }, inputHz);

    z2 = setInterval(function () {
        if (textContains("发送").exists() && text(keyword).exists() && !textContains("休息").exists()) {
            logCommon("发送：" + textContains("发送").findOne().click());
        } else if (id("ecv").exists() && text(keyword).exists() && !textContains("休息").exists()) {
            logCommon("发送：" + id("ecv").findOne().click());
        }
        if (stopAll) {
            // log("退出z2")
            clearInterval(z2);
        }
    }, sendHz);
}


/**
 * 查找商品点击
 * @param {*} itemButton 
 */
function findClickableItem(item) {
    var checkItem = item;
    while (true) {
        if (checkItem.clickable()) {
            // log("找到：" + checkItem);
            return checkItem;
        } else {
            // log("没找到，找父类")
            checkItem = checkItem.parent();
            if (checkItem == null) {
                // log("找不到")
                return item;
            } else {
                // log("找到父类：" + checkItem)
            }
        }
    }
}


//*******************************************************************日志处理***************************************************************************************** */
// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}

//*******************************************************************日志处理***************************************************************************************** */


//*******************************************************************基础方法***************************************************************************************** */
//打开浮窗
function openConsole() {
    auto.waitFor()
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}

function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var ms = time.getMilliseconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s) + ":" + add00(ms);
}

// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    return now;
}

//*******************************************************************基础方法***************************************************************************************** */
